<?php

namespace App\Model;

use App\Common\Exception\ThrowException;
use App\Common\Library\Util;
use EasySwoole\Utility\File;

class  Picture extends BaseModel
{
    private $savePath = 'storage/uploads/';
    private $saveUrl = '';

    /**
     * 设置保存路径
     * @param $savePath
     */
    public function setSavePath($savePath)
    {
        $this->savePath = $savePath;
        //判断目录是否存在不存在则创建目录
    }

    /**
     * 设置保存的url
     * @param $saveUrl
     */
    public function setSaveUrl($saveUrl)
    {
        $this->saveUrl = $saveUrl;
    }

    /**
     *  上传
     * @param $imgFile
     * @return array|\EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws ThrowException
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function upload($imgFile)
    {
        echo '-------------->>>'.$this->savePath.'<----';
        $this->createDir($this->savePath);
        $md5 = hash_file('md5', $imgFile->getTempName());
        $sha1 = hash_file('sha1', $imgFile->getTempName());
        $pictureOne = $this->findOne(['md5' => $md5, 'sha1' => $sha1]);
        if (!empty($pictureOne)) {  //当在数据库中查询到此图片时候就不用在上传
            return $pictureOne;
        }
        $uniqid = uniqid();
        $type = $imgFile->getClientMediaType();
        $saveName = $uniqid . '.' . Util::getExtByFileType($type);
        $data = array(
            'path' => $this->savePath . $saveName,
            'url' => $this->saveUrl,
            'md5' => $md5,
            'sha1' => $sha1,
        );
        if ($imgFile->moveTo($this->savePath . $saveName)) {
            if ($id = $this->addData($data)) {
                $data["id"] = $id;
                return $data;
            } else {
                throw  new ThrowException(ThrowException::ERROR_FILE_UPLOAD);
            }
            return $data;
        } else {
            throw  new ThrowException(ThrowException::ERROR_FILE_UPLOAD);
        }
    }
    /**
     * 创建目录
     * @param string $dirPath 需要创建的目录
     * @param integer $permissions 目录权限
     * @return bool
     * @author : evalor <master@evalor.cn>
     */
    public static function createDir($dirPath, $permissions = 0755)
    {
        echo $dirPath;
        return File::createDirectory($dirPath, $permissions);
    }
}